package com.faithbj.printer.service.Impl;

import java.util.Stack;

import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.springframework.stereotype.Component;

import com.faithbj.printer.service.WindowOperationService;

//@Component("windowOperator")
public class WindowOperationServiceImpl implements WindowOperationService {

	@Override
	public void closeCurrentWindow(WebDriver driver,
			Stack<String> historyWindowHandles) {
		if(historyWindowHandles.size()>0){
			driver.close();
			driver.switchTo().window(historyWindowHandles.pop());
		}
	}

	@Override
	public void swithToNewWindow(WebDriver driver,
			Stack<String> historyWindowHandles) {
		String curHandle = driver.getWindowHandle();
		for(String handle : driver.getWindowHandles()){
			if(!historyWindowHandles.contains(handle)&&!handle.equals(curHandle)){
				driver.switchTo().window(handle);
				historyWindowHandles.push(curHandle);
				break;
			}
		}
	}

	@Override
	public void acceptAlert(WebDriver driver) {
		Alert alert = driver.switchTo().alert();
        alert.accept();
	}

	@Override
	public void cleanIdleWindows(WebDriver driver) {
		String windowHandle = driver.getWindowHandle();
		this.cleanIdleWindows(driver, windowHandle);
	}

	@Override
	public void cleanIdleWindows(WebDriver driver, String windowHandle) {
		for(String handle:driver.getWindowHandles()){
			if(!handle.equals(windowHandle)){
				driver.switchTo().window(handle).close();
			}
		}
		driver.switchTo().window(windowHandle);
	}

	@Override
	public void cleanIdleWindows(WebDriver driver,
			Stack<String> historyWindowHandles) {
		while(historyWindowHandles.size()>0){
			driver.close();
			driver.switchTo().window(historyWindowHandles.pop());
		}
	}

}
